package com.horizon.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.horizon.common.entity.Token;
import com.horizon.common.util.SecrecyUtil;
import com.horizon.common.util.StringUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.time.Instant;

/**
 * Token鉴权拦截器
 *
 * @author wangfuwei
 * @version 2018-08-13
 */
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")) return true;

        String tokenStr = request.getHeader(Token.TOKEN_KEY);
        if (StringUtil.isEmpty(tokenStr)) {
            PrintWriter writer = response.getWriter();
            JSONObject error = new JSONObject();
            error.put("code", "401");
            error.put("msg", "token is missing");
            writer.write(error.toJSONString());
            return false;
        }

        Token token = SecrecyUtil.parseToken(tokenStr);
        if (token == null) {
            PrintWriter writer = response.getWriter();
            JSONObject error = new JSONObject();
            error.put("code", "401");
            error.put("msg", "token is error");
            writer.write(error.toJSONString());
            return false;
        }

        if (token.getExpiryTime().isBefore(Instant.now())) {//过期
            PrintWriter writer = response.getWriter();
            JSONObject error = new JSONObject();
            error.put("code", "401");
            error.put("msg", "token is expiry");
            writer.write(error.toJSONString());
            return false;
        }

        //刷新token过期时间
        response.setHeader(Token.TOKEN_KEY, SecrecyUtil.generateToken(token.refresh()));

        //设置线程变量
        Token.TOKEN_LOCAL.set(token);
        return true;
    }
}
